﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Candy
{
    public partial class WebcamChildWindow : ChildWindow
    {
        public WriteableBitmap CapturedPhoto { get; set; }

        public WebcamChildWindow()
        {
            InitializeComponent();
            base.Loaded += new RoutedEventHandler(ChildWindow1_Loaded);
        }
        void ChildWindow1_Loaded(object sender, RoutedEventArgs e)
        {
            StartWebCam();
        }
        // Offer ESC key support for closing the ChildWindow:
        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                captureSource.Stop();
                DialogResult = false;
                e.Handled = true;
            }

            base.OnKeyDown(e);
        }

        public CaptureSource captureSource;
        private void StartWebCam()
        {
            if (captureSource == null)
            {
                // Create new CaptureSource if first run
                captureSource = new CaptureSource();
                captureSource.CaptureImageCompleted += new EventHandler<CaptureImageCompletedEventArgs>(captureSource_CaptureImageCompleted);
            }
            else
            {
                // Stops old source if second run
                captureSource.Stop();

            }

            // Set VideoCaptureDevice to selected WebCam
            captureSource.VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

            // Create VideoBrush to paint WebCam preview
            VideoBrush PreviewBrush = new VideoBrush();
            PreviewBrush.Stretch = Stretch.Uniform;
            PreviewBrush.SetSource(captureSource);
            ViewPort.Fill = PreviewBrush;

            // Start capture source
            captureSource.Start();
        }

        void captureSource_CaptureImageCompleted(object sender, CaptureImageCompletedEventArgs e)
        {

            captureSource.Stop();
            CapturedPhoto = e.Result;
            this.DialogResult = true;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            captureSource.CaptureImageAsync();


        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            captureSource.Stop();
            this.DialogResult = false;
        }
    }
}

